package JZOffer;

// https://leetcode.cn/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/?envType=study-plan&id=lcof&plan=lcof&plan_progress=xxj1ozje
// 两个链表的第一个公共节点
public class Day012_2 {
    ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode c1 = headA;
        ListNode c2 = headB;

        int s1 = 0;
        int s2 = 0;
        while (c1 != null) {
            c1 = c1.next;
            s1 ++;
        }
        while (c2 != null) {
            c2 = c2.next;
            s2 ++;
        }
        c1 = headA;
        c2 = headB;

        if (s1 > s2) {
            for (int i = 0; i < s1-s2; i++) {
                c1 = c1.next;
            }
        } else {
            for (int i = 0; i < s2-s1; i++) {
                c2 = c2.next;
            }
        }

        while (c1 != null && c2 != null && c1 != c2) {
            c1 = c1.next;
            c2 = c2.next;
        }
        return c1;
    }
}
